﻿using System.IO;
using HKTools;
using UnityEditor;
using UnityEngine;

/// <summary>
/// SerialPortConfig配置文件管理
/// </summary>
public class HK_GenerateSerialPortConfig : EditorWindow
{
    string jsonStr = "{\r\n  \"PortName\": \"COM3\",\r\n  \"BaudRate\": 9600,\r\n  \"Parity\": \"None\",\r\n  \"DataBits\": 8,\r\n  \"StopBits\": \"None\"\r\n}";

    string configPath = Path.Combine(Application.streamingAssetsPath, "HK_SerialConfig.json");

    [MenuItem("HKTools/GenerateSerialPortConfig(生成串口配置文件)", priority = HK_MenuPriority.HK_SerialPort)]
    static void Init()
    {
        HK_GenerateSerialPortConfig serialPortConfig = GetWindow<HK_GenerateSerialPortConfig>("生成串口配置文件");
        serialPortConfig.Show();
    }

    void OnGUI()
    {
        GUILayout.Space(15);

        if (GUILayout.Button("生成 HK_SerialConfig.json"))
        {
            if (File.Exists(configPath))
            {
                Debug.LogWarning("串口配置文件已存在！");
                return;
            }

            // 如果没有StreamingAssets文件夹
            if (!Directory.Exists(Application.streamingAssetsPath))
            {
                Directory.CreateDirectory(Application.streamingAssetsPath);
            }

            File.Create(configPath).Close();

            File.WriteAllText(configPath, jsonStr);

            Debug.LogWarning("串口配置文件已生成！");

            AssetDatabase.Refresh();
        }

        GUILayout.Space(10);

        if (GUILayout.Button("重置 HK_SerialConfig.json"))
        {
            if (!File.Exists(configPath) || !Directory.Exists(Application.streamingAssetsPath))
            {
                Debug.LogWarning("串口配置文件不存在！请先生成");
                return;
            }

            File.WriteAllText(configPath, jsonStr);

            Debug.LogWarning("串口配置文件已重置！");

            AssetDatabase.Refresh();
        }
    }
}
